package com.learning.mybatis.plugin.application.plugin.readingwritingseparation;

import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * ClassName: MultiDataSourceConfig
 * Description: 自定义多数据源
 * Date: 2018/1/2 14:45 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
//@Configuration
//@EnableTransactionManagement
public class MultiDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource-one")
    public DataSource oneDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource-two")
    public DataSource twoDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public DynamicDataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setWriteDataSource(oneDataSource());
        dynamicDataSource.setReadDataSource(twoDataSource());
        return dynamicDataSource;
    }

    @Bean
    public DataSourceTransactionManager twoTransaction() {
        DataSourceTransactionManager txName = new DataSourceTransactionManager();
        txName.setDataSource(dataSource());
        return txName;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        /** 设置实体别名 typeAlias 包扫描路径 */
        bean.setTypeAliasesPackage("");
        /** 添加mapper.xml 扫描路径 */
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources(""));
        } catch (IOException e) {
            throw new RuntimeException("MyBatis Read MapperLocations Error", e);
        }

        /** 设置mybatis configuration 扫描路径 */
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setDefaultStatementTimeout(25000);
        bean.setConfiguration(configuration);

        // 动态插件
        DynamicDataSourceInterceptor dynamicDataSourceInterceptor = new DynamicDataSourceInterceptor();
        bean.setPlugins(new Interceptor[]{dynamicDataSourceInterceptor});


        return bean;
    }
}
